<template>
  <el-tabs v-model="activeName" style="padding:20px; background:#FFF" type="card" @tab-click="syncSkuNumber">
    <el-tab-pane label="套餐信息" name="first">
      <div class="main package-container">
        <section v-loading.fullscreen.lock="goodsLoading">
          <div class="section-header">
            <span v-text="id ? pageTypes[$route.query.pageType]: '套餐新建'"></span>
          </div>
          <el-form class="section-content" :model="formData" :rules="formRules" size="medium" ref="form" label-width="150px" :disabled="$route.query.pageType==='view'">
            <el-form-item label="套餐名称:" prop="packageRequest.name">
              <el-input v-model="formData.packageRequest.name"></el-input>
            </el-form-item>
            <el-form-item label="套餐副标题:" prop="packageRequest.subTitle">
              <el-input v-model="formData.packageRequest.subTitle"></el-input>
            </el-form-item>
            <el-form-item label="套餐商品:" prop="packageGoodsList">
              <el-button type="primary" plain @click="chooseGoods" :disabled="!!isEdit">选择商品</el-button>
            </el-form-item>
            <el-form-item v-if="formData.packageGoodsList.length > 0">
              <div v-for="(goods, index) of formData.packageGoodsList" :key="index" style="margin-bottom: 22px">
                <el-row justify="space-between" style="border: 1px solid #eee; border-bottom: 0; padding-left: 12px">
                  <el-col :span="12">
                    <a
                      v-if="!isEdit"
                      href="javascript: void(0);"
                      class="el-icon-remove"
                      style="color: red; font-size: 16px"
                      @click="delGoods(index)"
                    ></a>
                    {{goods.goodsName}}
                  </el-col>
                  <el-col :span="12">
                    <div style="text-align: right">
                      <!--<template v-if="isEdit&&!(formData.packageRequest.upshelf!==1&&formData.packageRequest.autoUpShelfFlag !== 1)&&$route.query.pageType!=='view'">
                                        <el-button type="text" v-if="!goods.editSku" @click="goods.editSku = true" style="margin-right: 12px">修改库存</el-button>
                                        <el-button type="text" v-else @click="modifySku(index)" style="margin-right: 12px">保存</el-button>
                                    </template>-->
                      <el-checkbox
                        :true-label="0"
                        :false-label="1"
                        v-model="goods.packageGoodsType"
                        :disabled="!!isEdit"
                        @change="reValidate"
                      >设为赠品</el-checkbox>
                    </div>
                  </el-col>
                </el-row>
                <!--<el-tag :key="goods.id" :closable="!isEdit" @close="delGoods(index)">{{goods.goodsName}}</el-tag>
                    <el-checkbox :true-label="0" :false-label="1" v-model="goods.packageGoodsType" :disabled="!!isEdit" @change="reValidate">设为赠品</el-checkbox>-->
                <el-table v-if="goods.goodsAttr.length" :data="goods.goodsAttr.filter(item=>item.deleteFlag!==0)" border highlight-current-row>
                  <template v-for="(item, attrIndex) in [{id: 'attrId1',prop: 'attrValue1'},{id:'attrId2',prop: 'attrValue2'},{id:'attrId3',prop: 'attrValue3'},{id:'attrId4',prop: 'attrValue4'},{id:'attrId5',prop: 'attrValue5'},{id:'attrId6',prop: 'attrValue6'}]">
                    <el-table-column
                      v-if="goods.goodsAttr[0][item.id]"
                      :key="attrIndex"
                      align="center"
                      :label="'属性值'+(attrIndex+1)"
                      :prop="item.prop"
                      min-width="100px"
                    >
                    </el-table-column>
                  </template>

                  <!--<el-table-column align="center" label="财务价">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].financePrice'" :rules="commonRules.priceRuleNull" style="margin: 20px 0">
                                        <el-input type="number" v-model="scope.row.financePrice" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="成本价">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].costPrice'"  :rules="commonRules.priceRuleNull" style="margin: 20px 0">
                                        <el-input type="number" v-model="scope.row.costPrice" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>-->
                  <el-table-column align="center" label="市场价">
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].marketValue'"
                        :rules="commonRules.priceRule"
                        style="margin: 30px 0"
                      >
                        <el-input
                          type="number"
                          v-model="scope.row.marketValue"
                          style="width: 100%"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="销售价">
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].price'"
                        :rules="commonRules.priceRule"
                        style="margin: 30px 0"
                      >
                        <el-input
                          type="number"
                          v-model="scope.row.price"
                          style="width: 100%"
                          @change="calcOtherPrice(index, scope.$index)"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="VIP价">
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].regionPrice'"
                        :rules="{required: true, message: '不能为空', trigger: 'change'}"
                        style="margin: 20px 0"
                      >
                      <!-- scope.row.maximumCommission == 0?scope.row.prive:scope.row.regionPrice-->
                        <el-input
                          type="number"
                          placeholder="自动生成"
                          v-model="scope.row.maximumCommission == 0?scope.row.price:scope.row.regionPrice"
                          style="width: 100%"
                          disabled
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="钻石价">
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].diamondPrice'"
                        :rules="{required: true, message: '不能为空', trigger: 'change'}"
                        style="margin: 20px 0"
                      >
                        <el-input
                          type="number"
                          placeholder="自动生成"
                          v-model="scope.row.maximumCommission == 0?scope.row.price:scope.row.diamondPrice||0"
                          style="width: 100%"
                          disabled
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="董事价">
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].directorPrice'"
                        :rules="{required: true, message: '不能为空', trigger: 'change'}"
                        style="margin: 20px 0"
                      >
                        <el-input
                          type="number"
                          placeholder="自动生成"
                          v-model="scope.row.maximumCommission == 0?scope.row.price:scope.row.directorPrice"
                          style="width: 100%"
                          disabled
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <!--<el-table-column align="center" label="佣金类型" min-width="98px">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].commissionType'" :rules="{required: true, message: '不能为空', trigger: 'change'}" style="margin: 30px 0">
                                        <el-select v-model="scope.row.commissionType">
                                            <el-option :key="1" label="数值(元)" :value="1"></el-option>
                                            <el-option :key="2" label="比例(%)" :value="2"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="佣金数值">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].commission'" :rules="scope.row.commissionType===1?commonRules.priceRule : commonRules.percentRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="scope.row.commission" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>-->
                  <el-table-column align="center" label="最高佣金">
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].maximumCommission'"
                        :rules="commonRules.priceRuleZero"
                        style="margin: 30px 0"
                      >
                        <el-input
                          type="number"
                          placeholder="小于兰蜜价"
                          v-model="scope.row.maximumCommission"
                          style="width: 100%"
                          @change="calcOtherPrice(index, scope.$index)"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="库存数"
                    prop="totalSkuNumber"
                    min-width="100px"
                  >
                    <template slot-scope="scope">
                      {{scope.row.totalSkuNumber}}
                      <div
                        v-if="!scope.row.totalSkuNumber"
                        style="color: red"
                      >库存不足</div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="已售"
                    prop="soldNumber"
                    min-width="100px"
                  ></el-table-column>
                  <!--<el-table-column align="center" label="库存数" min-width="90px">
                                <template slot-scope="scope">
                                    <template v-if="goods.goodsType==1">
                                        可分配：{{scope.row.totalSkuNumber}}<br/>
                                        已售：{{(scope.row.soldNumber||0)}}<br/>
                                        可卖：{{(scope.row.distributedSkuNumber||0)}}<br/>
                                        <el-form-item v-if="scope.row.totalSkuNumber+(scope.row.distributedSkuNumber||0)" :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].skuNumber'" :rules="commonRules.skuNumberRule" style="margin-bottom: 30px">
                                            <el-input-number v-model.number="scope.row.skuNumber" :disabled="!isEdit||(formData.packageRequest.upshelf!==1&&formData.packageRequest.autoUpShelfFlag !== 1)||!goods.editSku" :min="0" :max="scope.row.totalSkuNumber+(scope.row.distributedSkuNumber||0)" :precision="0" :controls="false" style="width: 100%"></el-input-number>
                                        </el-form-item>
                                        <span v-else style="color: red">库存不足</span>
                                    </template>
                                    <template v-else>
                                        <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].skuNumber'" :rules="commonRules.skuNumberRule" style="margin: 30px 0">
                                            <el-input-number v-model.number="scope.row.skuNumber" :disabled="formData.packageRequest.type === 1" :min="1" :max="9999999" :precision="0" :controls="false" style="width: 100%"></el-input-number>
                                        </el-form-item>
                                    </template>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="数量" min-width="70px">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].packageGoodsNumber'" :rules="commonRules.numberRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="scope.row.packageGoodsNumber" style="width: 100%" disabled></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="是否上架" width="80">
                                <template slot-scope="scope">
                                    <el-switch
                                            v-model="scope.row.upshelf"
                                            active-color="#13ce66"
                                            inactive-color="#ff4949"
                                            :active-value="1"
                                            :inactive-value="0">
                                    </el-switch>
                                </template>
                            </el-table-column>-->
                  <el-table-column
                    v-if="!isEdit && goods.goodsAttr.filter(item=>item.deleteFlag!==0).length>1"
                    align="center"
                    label="操作"
                    width="60"
                    fixed="right"
                  >
                    <template slot-scope="scope">
                      <a
                        href="javascript: void(0);"
                        class="el-icon-remove"
                        @click="delAttrVal(goods.goodsAttr, scope.$index)"
                      ></a>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-form-item>
            <!--<el-form-item label="套餐赠品:">
                    <el-button type="primary" plain @click="chooseGoods(0)" :disabled="!!isEdit">选择商品</el-button>
                </el-form-item>
                <el-form-item v-if="formData.packageGoodsList.filter(item=>item.packageGoodsType===0).length > 0">
                    <div v-for="(goods, index) of formData.packageGoodsList" v-if="goods.packageGoodsType===0" style="border: 0px solid #eee; margin-bottom: 25px">
                        <el-tag :key="goods.id" :closable="!isEdit" @close="delGoods(index)">{{goods.goodsName}}</el-tag>
                        &lt;!&ndash;<el-checkbox :true-label="0" :false-label="1" v-model="goods.packageGoodsType" :disabled="!!isEdit" @change="reValidate">设为赠品</el-checkbox>&ndash;&gt;
                        <el-table v-if="goods.goodsAttr.length" :data="goods.goodsAttr" border highlight-current-row>
                            <el-table-column v-for="(item, index) in [{id: 'attrId1',prop: 'attrValue1'},{id:'attrId2',prop: 'attrValue2'},{id:'attrId3',prop: 'attrValue3'},{id:'attrId4',prop: 'attrValue4'},{id:'attrId5',prop: 'attrValue5'},{id:'attrId6',prop: 'attrValue6'}]" v-if="goods.goodsAttr[0][item.id]" :key="index" align="center" :label="'属性值'+(index+1)" :prop="item.prop" min-width="100px">
                            </el-table-column>
                            <el-table-column align="center" label="财务价">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].financePrice'" :rules="commonRules.priceRuleNull" style="margin: 20px 0">
                                        <el-input type="number" v-model="scope.row.financePrice" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="成本价">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].costPrice'"  :rules="commonRules.priceRuleNull" style="margin: 20px 0">
                                        <el-input type="number" v-model="scope.row.costPrice" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="市场价">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].marketValue'" :rules="commonRules.priceRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="scope.row.marketValue" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="兰蜜价">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].price'" :rules="commonRules.priceRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="scope.row.price" style="width: 100%" @change="calcOtherPrice(index, scope.$index)"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="大区价">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].regionPrice'" :rules="{required: true, message: '不能为空', trigger: 'change'}" style="margin: 20px 0">
                                        <el-input type="number" placeholder="自动生成" v-model="scope.row.regionPrice" style="width: 100%" disabled></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="董事价">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].directorPrice'" :rules="{required: true, message: '不能为空', trigger: 'change'}" style="margin: 20px 0">
                                        <el-input type="number" placeholder="自动生成" v-model="scope.row.directorPrice" style="width: 100%" disabled></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            &lt;!&ndash;<el-table-column align="center" label="佣金类型" min-width="98px">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].commissionType'" :rules="{required: true, message: '不能为空', trigger: 'change'}" style="margin: 30px 0">
                                        <el-select v-model="scope.row.commissionType">
                                            <el-option :key="1" label="数值(元)" :value="1"></el-option>
                                            <el-option :key="2" label="比例(%)" :value="2"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="佣金数值">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].commission'" :rules="scope.row.commissionType===1?commonRules.priceRule : commonRules.percentRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="scope.row.commission" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>&ndash;&gt;
                            <el-table-column align="center" label="最高佣金">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].maximumCommission'" :rules="commonRules.priceRuleZero" style="margin: 30px 0">
                                        <el-input type="number" placeholder="小于兰蜜价" v-model="scope.row.maximumCommission" style="width: 100%" @change="calcOtherPrice(index, scope.$index)"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="库存数" min-width="90px">
                                <template slot-scope="scope">
                                    可分配：{{scope.row.totalSkuNumber}}<br/>
                                    已分配：{{(scope.row.distributedSkuNumber||0)+(scope.row.soldNumber||0)}}<br/>
                                    <el-form-item v-if="scope.row.totalSkuNumber+(scope.row.distributedSkuNumber||0)" :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].skuNumber'" :rules="commonRules.skuNumberRule" style="margin-bottom: 30px">
                                        <el-input-number v-model="scope.row.skuNumber" :disabled="formData.packageRequest.type === 1" :min="1" :max="scope.row.totalSkuNumber+(scope.row.distributedSkuNumber||0)" :precision="0" :controls="false" style="width: 100%"></el-input-number>
                                    </el-form-item>
                                    <span v-else style="color: red">库存不足</span>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="数量" min-width="70px">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].packageGoodsNumber'" :rules="commonRules.numberRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="scope.row.packageGoodsNumber" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="是否上架" width="80">
                                <template slot-scope="scope">
                                    <el-switch
                                            v-model="scope.row.upshelf"
                                            active-color="#13ce66"
                                            inactive-color="#ff4949"
                                            :active-value="1"
                                            :inactive-value="0">
                                    </el-switch>
                                </template>
                            </el-table-column>
                            <el-table-column v-if="!isEdit && goods.goodsAttr.length>1" align="center" label="操作" width="60" fixed="right">
                                <template slot-scope="scope">
                                    <a href="javascript: void(0);" class="el-icon-remove" @click="delAttrVal(goods.goodsAttr, scope.$index)"></a>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-form-item>-->
            <el-form-item
              label="套餐类型:"
              prop="packageRequest.type"
            >
              <el-radio
                v-model="formData.packageRequest.type"
                :key="1"
                :label="1"
                :disabled="!!isEdit"
              >固定模式</el-radio>
              <el-radio
                v-model="formData.packageRequest.type"
                :key="2"
                :label="2"
                :disabled="!!isEdit"
              >自由组合模式</el-radio>
            </el-form-item>
            <el-form-item
              label="仓库:"
              prop="packageRequest.cangku"
              v-if="formData.packageRequest.cangku"
            >
              {{formData.packageRequest.cangku}}
              <!--<el-input type="number" v-model="formData.packageRequest.cangku"></el-input>-->
            </el-form-item>
            <el-form-item
              label="商品数量:"
              prop="packageRequest.num"
              v-if="formData.packageRequest.type === 2"
            >
              <el-input
                type="number"
                v-model="formData.packageRequest.num"
              ></el-input>
            </el-form-item>
            <el-form-item v-if="id" label="业务首次上架时间:" style="width:650px;" class="hide-close">
              <el-date-picker
                :disabled="!formData.packageRequest.firstUpSelfTime"
                v-model="formData.packageRequest.firstUpSelfTime"
                value-format="yyyy-MM-dd hh:mm:ss"
                type="datetime"
                placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item
              label="赠品数量:"
              prop="packageRequest.presentSelectedNum"
              v-if="formData.packageGoodsList.some(item=>item.packageGoodsType===0)"
            >
              <el-input
                type="number"
                v-model="formData.packageRequest.presentSelectedNum"
              ></el-input>
            </el-form-item>
            <!--<el-form-item label="套餐数量:" prop="packageRequest.packageNumber">
                    <el-input type="number" v-model="formData.packageRequest.packageNumber" @change="()=>{calcSku()}"></el-input>
                </el-form-item>-->
            <el-form-item
              label="市场价:"
              prop="packageRequest.marketValue"
            >
              <el-input
                type="number"
                v-model="formData.packageRequest.marketValue"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="销售价:"
              prop="packageRequest.price"
            >
              <el-input
                type="number"
                v-model="formData.packageRequest.price"
                @change="calcPrice"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="VIP价:"
              prop="packageRequest.regionPrice"
            >
              <el-input
                type="number"
                v-model="formData.packageRequest.maximumCommission == 0?formData.packageRequest.price:formData.packageRequest.regionPrice"
                placeholder="自动生成"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item
              label="钻石价:"
              prop="packageRequest.diamondPrice"
            >
              <el-input
                type="number"
                v-model="formData.packageRequest.maximumCommission == 0?formData.packageRequest.price:formData.packageRequest.diamondPrice||0"
                placeholder="自动生成"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item
              label="董事价:"
              prop="packageRequest.directorPrice"
            >
              <el-input
                type="number"
                v-model="formData.packageRequest.maximumCommission == 0?formData.packageRequest.price:formData.packageRequest.directorPrice"
                placeholder="自动生成"
                disabled
              ></el-input>
            </el-form-item>
            <!--<el-form-item label="佣金类型:" prop="packageRequest.commissionType">
                    <el-select v-model="formData.packageRequest.commissionType">
                        <el-option :key="1" label="数值(元)" :value="1"></el-option>
                        <el-option :key="2" label="比例(%)" :value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="佣金数值:" prop="packageRequest.commission">
                    <el-input type="number" v-model="formData.packageRequest.commission"></el-input>
                </el-form-item>-->
            <el-form-item
              label="最高佣金:"
              prop="packageRequest.maximumCommission"
              :rules="commonRules.priceRuleZero"
            >
              <el-input
                type="number"
                placeholder="须小于兰蜜价"
                v-model="formData.packageRequest.maximumCommission"
                @change="calcPrice"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="是否打折:"
              prop="packageRequest.packagePricingType"
            >
              <el-switch
                v-model="formData.packageRequest.packagePricingType"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="是"
                inactive-text="否"
                :active-value="2"
                :inactive-value="1"
              >
              </el-switch>
            </el-form-item>
            <el-form-item
              label="折扣:"
              prop="packageRequest.discount"
              v-if="formData.packageRequest.packagePricingType === 2"
            >
              <el-input
                type="number"
                v-model="formData.packageRequest.discount"
              >
                <template slot="append">折</template>
              </el-input>
            </el-form-item>
            <el-form-item
              label="用户限购数量:"
              prop="packageRequest.userQuantity"
            >
              <el-input
                type="number"
                v-model="formData.packageRequest.userQuantity"
              ></el-input> 填 0 代表不限购
            </el-form-item>
            <el-form-item
              label="套餐主图:"
              prop="packageRequest.image"
            >
              <el-upload
                class="avatar-uploader"
                accept="image/*"
                :action="upladUrl"
                name="file"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :on-success="uploadSuccess"
              >
                <img
                  v-if="formData.packageRequest.image"
                  :src="formData.packageRequest.image"
                  class="avatar"
                >
                <i
                  v-else
                  class="el-icon-plus avatar-uploader-icon"
                ></i>
              </el-upload>
            </el-form-item>
            <el-form-item
              label="套餐图片:"
              prop="packageGalleryList"
            >
              <ul class="upload-img-list">
                <li class="img-preview" v-for="(item, index) of formData.packageGalleryList" :key="index">
                  <img :src="item.url" alt="">
                  <div class="img-preview-mask" v-if="$route.query.pageType!=='view'">
                    <div class="mask-btn">
                      <i
                        title="删除"
                        class="el-icon-delete"
                        @click="delImg(index)"
                      ></i>
                    </div>
                  </div>
                </li>
                <li v-if="$route.query.pageType!=='view'">
                  <label class="upload-btn">
                    <input
                      type="file"
                      accept="image/*"
                      @change="uploadImg"
                    />
                    <i class="el-icon-plus"></i>
                  </label>
                </li>
              </ul>
            </el-form-item>
            <el-form-item
              label="套餐说明:"
              prop="packageRequest.remarks"
            >
              <el-input
                type="textarea"
                v-model="formData.packageRequest.remarks"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="套餐故事:"
              prop="packageRequest.story"
            >
              <el-input
                type="textarea"
                v-model="formData.packageRequest.story"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="套餐详情:"
              prop="packageRequest.intro"
            >
              <tinymce
                :height="360"
                v-model="formData.packageRequest.intro"
              ></tinymce>
            </el-form-item>
            <el-form-item
              label="运费模板:"
              prop="packageRequest.freightTemplateId"
            >
              <el-select
                v-model="formData.packageRequest.freightTemplateId"
                placeholder="请选择"
                filterable
                clearable
              >
                <el-option
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  v-for="item in freightList"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="销售数量:"
              prop="packageRequest.fakeSoldNumber"
            >
              <el-input v-model="formData.packageRequest.fakeSoldNumber"></el-input>
            </el-form-item>
            <el-form-item
              label="套餐标签:"
              prop="tags"
            >
              <input
                type="checkbox"
                id="tag-more"
                class="tag-checkbox-group-switch"
                v-model="tagMore"
              />
              <el-checkbox-group
                v-model="tempTagCheck"
                class="tag-checkbox-group-more"
              >
                <el-checkbox
                  v-for="item in tags"
                  :key="item.id"
                  :label="item.id"
                >{{item.name}}</el-checkbox>
                <label
                  for="tag-more"
                  class="tag-checkbox-group-more-btn"
                  v-text="tagMore ? '收起' : '更多'"
                ></label>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
          <el-form
            class="section-content"
            :model="formData"
            size="medium"
            label-width="150px"
          >
            <template v-if="isEdit">
              <el-form-item
                label="是否上架:"
                prop="packageRequest.upshelf"
              >
                <el-switch
                  v-model="formData.packageRequest.upshelf"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="是"
                  inactive-text="否"
                  :active-value="1"
                  :inactive-value="0"
                  @change="changeIsSell"
                  :disabled="$route.query.pageType==='view'"
                >
                </el-switch>
              </el-form-item>
              <template v-if="formData.packageRequest.upshelf === 0">
                <el-form-item
                  label="是否自动上下架:"
                  prop="packageRequest.autoUpShelfFlag"
                >
                  <el-switch
                    v-model="formData.packageRequest.autoUpShelfFlag"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-text="是"
                    inactive-text="否"
                    :active-value="1"
                    :inactive-value="0"
                    @change="changeIsSell"
                    :disabled="$route.query.pageType==='view'"
                  >
                  </el-switch>
                </el-form-item>
                <el-form-item
                  label="上下架时间:"
                  prop="packageRequest.timeRange"
                  v-if="formData.packageRequest.autoUpShelfFlag === 1"
                >
                  <el-date-picker
                    v-model="formData.packageRequest.timeRange"
                    type="datetimerange"
                    range-separator="~"
                    start-placeholder="上架时间"
                    end-placeholder="下架时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :disabled="$route.query.pageType==='view'"
                  >
                  </el-date-picker>
                </el-form-item>
              </template>
              <el-form-item
                label="是否售卖:"
                prop="packageRequest.isSell"
              >
                <el-switch
                  v-model="formData.packageRequest.isSell"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="是"
                  inactive-text="否"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="$route.query.pageType==='view'"
                >
                </el-switch>
              </el-form-item>
              <el-form-item
                label="是否允许被搜索:"
                prop="packageRequest.isSearched"
              >
                <el-switch
                  v-model="formData.packageRequest.isSearched"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="是"
                  inactive-text="否"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="$route.query.pageType==='view'"
                >
                </el-switch>
              </el-form-item>
              <el-form-item
                label="开售时间:"
                prop="packageRequest.sellTime"
                v-if="formData.packageRequest.isSell === 0"
                :rules="commonRules.notNullRule"
              >
                <el-date-picker
                  v-model="formData.packageRequest.sellTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :disabled="$route.query.pageType==='view'"
                >
                </el-date-picker>
              </el-form-item>
            </template>
            <el-form-item>
              <el-button
                v-if="$route.query.pageType!=='view'"
                type="success"
                @click="save"
                :loading="btnLoading"
              >保存</el-button>
              <el-button
                v-if="$route.query.pageType==='view' && formData.packageRequest.upshelf === 1"
                type="danger"
                @click="offShelves"
                :loading="btnLoading"
              >下架</el-button>
              <el-button
                class="filter-item"
                type="primary"
                plain
                @click="$router.push({name: 'activityPackage'})"
              >返回</el-button>
            </el-form-item>
          </el-form>
        </section>
      </div>
    </el-tab-pane>
    <el-tab-pane
      label="评论列表"
      name="second"
    >
      <CommontTable
        v-if='commontGoods.length > 0'
        :goods="commontGoods"
        :goodsType="2"
      />
    </el-tab-pane>
    <el-tab-pane
      label="套餐上下架记录"
      name="log"
    >
      <el-table :data="goodsLogList" v-loading="listLoading" header-row-class-name="table-header" element-loading-text="给我一点时间" border highlight-current-row>
        <el-table-column align="center" label="姓名" prop="operatorName" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="手机号" prop="operatorMobile" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="动作" prop="actionName" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="操作时间" prop="updateTime" show-overflow-tooltip></el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="listQuery.pageSize"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="listTotal">
      </el-pagination>
    </el-tab-pane>
  </el-tabs>

</template>
<script>
// import differenceBy from 'lodash/differenceBy';
import { regexp } from '../../../utils/tools'
import Tinymce from '@/components/Tinymce'
import { getTagList, upload } from '../../../api/common'
import { getAllList } from '@/api/freight'
import CommontTable from '@/components/CommontTable'
export default {
  name: 'activityPackageEdit',
  components: {
    Tinymce,
    CommontTable
  },
  props: {
    id: {
      default: ''
    }
  },
  inject: ['reload'],
  computed: {
    isEdit() {
      return this.id && this.$route.name === 'activityPackageEdit'
    }
  },
  data() {
    const validPresentNum = (rule, value, callback) => {
      if (!value) {
        return callback()
      }
      if (!/^[1-9]\d*$/.test(value)) {
        return callback(new Error('必须为正整数'))
      }
      let maxNum = 0
      this.formData.packageGoodsList.map(item => {
        if (item.packageGoodsType === 0 && item.goodsAttr.length) {
          maxNum++
        }
      })
      if (maxNum < 1) {
        return callback(new Error('请先选择赠品'))
      }
      if (value > maxNum) {
        return callback(new Error('不能超过套餐赠品数量'))
      }
      return callback()
    }
    const validNum = (rule, value, callback) => {
      if (!value) {
        return callback()
      }
      if (!/^[1-9]\d*$/.test(value)) {
        return callback(new Error('必须为正整数'))
      }
      let maxNum = 0
      this.formData.packageGoodsList.map(item => {
        if (item.packageGoodsType === 1 && item.goodsAttr.length) {
          maxNum++
        }
      })
      if (maxNum < 1) {
        return callback(new Error('请先选择商品'))
      }
      if (value > maxNum) {
        return callback(new Error('不能超过套餐商品数量'))
      }
      return callback()
    }
    const validDiscount = (rule, value, callback) => {
      if (value <= 0 || !/^([1-9]{1}|(\d\.\d))$/.test(value)) {
        return callback(new Error('必须为大于0小于10，最多保留1位小数'))
      }
      return callback()
    }
    const validPackageGoodsList = (rule, value, callback) => {
      let maxNum = this.formData.packageGoodsList.filter(
        item => item.packageGoodsType === 1
      ).length
      console.log(this.formData.packageGoodsList)
      if (maxNum < 1) {
        return callback(new Error('请选择至少一个商品（非设置成赠品）'))
      }
      return callback()
    }
    const validPackageNumber = (rule, value, callback) => {
      if (value < 1) {
        return callback(new Error('必须大于0'))
      }
      if (this.formData.packageRequest.type === 1) {
        let goodsArray = []
        let skuNumArray = []
        this.formData.packageGoodsList.map(item => {
          if (
            item.goodsType === 1 /*&&item.packageGoodsType === 1*/ &&
            item.goodsAttr.length
          ) {
            let skuNum = 0
            let distributedSkuNum = 0
            item.goodsAttr.map(subItem => {
              if (subItem.deleteFlag) {
                skuNum += Math.floor(
                  ((subItem.distributedSkuNumber || 0) +
                    subItem.totalSkuNumber) /
                    subItem.packageGoodsNumber
                )
                distributedSkuNum += Math.floor(
                  (subItem.distributedSkuNumber || 0) /
                    subItem.packageGoodsNumber
                )
              }
              //skuNum+=((subItem.distributedSkuNumber||0) + subItem.totalSkuNumber)
            })

            if (goodsArray.some(subItem => subItem.goodsId === item.goodsId)) {
              let obj = goodsArray.find(
                subItem => subItem.goodsId === item.goodsId
              )
              obj.num = obj.num + 1
              obj.skuNum += distributedSkuNum
            } else {
              goodsArray.push({
                goodsId: item.goodsId,
                num: 1,
                skuNum
              })
            }
            // skuNumArray.push(skuNum)
          }
        })

        // console.log(goodsArray);
        goodsArray.map(item => {
          skuNumArray.push(Math.floor(item.skuNum / item.num))
        })
        console.log(skuNumArray)
        let minNum = Math.min.apply(null, skuNumArray)
        if (minNum < 1) {
          return callback(new Error('存在0库存套餐商品，请先移除'))
        } else if (value > minNum) {
          return callback(
            new Error('套餐数量必须小于等于套餐商品的最小库存数：' + minNum)
          )
        }
      }

      return callback()
    }
    return {
      listLoading: false, // 商品上下架记录表格loading
      listTotal: 0, // 套餐上下架记录 分页总数
      listQuery: { // 套餐上下架记录 分页
        pageIndex: 1,
        pageSize: 10,
      },
      goodsLogList: [], // 套餐上下架记录
      commontGoods: [], // 评论商品可选列表
      activeName: 'first',
      pageTypes: {
        view: '套餐查看',
        edit: '套餐编辑',
        upshelf: '套餐上架'
      },
      btnLoading: false,
      goodsLoading: false,
      presentGoodsLoading: false,
      tags: [],
      tagMore: false,
      tempTagCheck: [],
      tempGoodsCheck: [],
      tempPresentGoodsCheck: [],
      formData: {
        packageRequest: {
          name: '',
          type: 1,
          num: '',
          marketValue: '',
          price: '',
          regionPrice: '',
          directorPrice: '',
          diamondPrice: '',
          commissionType: 1,
          commission: '',
          maximumCommission: 0,
          packagePricingType: 1,
          discount: '',
          isEnable: '',
          upshelf: 0,
          isSell: 0,
          isSearched: 0,
          isPurchaseLimit: 1,
          timeRange: [],
          userQuantity: '',
          image: '',
          remarks: '',
          story: '',
          intro: '',
          firstUpSelfTime: '',
          freightTemplateId: '' //运费模板
        },
        packageGalleryList: [],
        packageGoodsList: [],
        packageTagList: [],
        goodsAttr: []
      },
      formRules: {
        'packageRequest.name': [
          { required: true, message: '不能为空', trigger: 'change' },
          { max: 100, message: '不能超过100字符', trigger: 'change' }
        ],
        packageGoodsList: [
          { required: true, message: '请选择商品', trigger: 'change' },
          { validator: validPackageGoodsList, trigger: 'change' }
        ],
        'packageRequest.presentSelectedNum': [
          { required: true, message: '不能为空', trigger: 'change' },
          { validator: validPresentNum, trigger: 'change' }
        ],
        'packageRequest.num': [
          { required: true, message: '不能为空', trigger: 'change' },
          { validator: validNum, trigger: 'change' }
        ],
        'packageRequest.packageNumber': [
          { required: true, message: '不能为空', trigger: 'change' },
          { validator: validPackageNumber, trigger: 'change' }
        ],
        'packageRequest.marketValue': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '价格必须大于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'packageRequest.price': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '价格必须大于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'packageRequest.regionPrice': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '价格必须大于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'packageRequest.directorPrice': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '价格必须大于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'packageRequest.commission': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '佣金必须大于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'packageRequest.maximumCommission': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.zMoney,
            message: '佣金必须大于等于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'packageRequest.discount': [
          { required: true, message: '不能为空', trigger: 'change' },
          { validator: validDiscount, trigger: 'change' }
        ],
        'packageRequest.userQuantity': [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        'packageRequest.image': [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        packageGalleryList: [
          { required: true, message: '请上传套餐图片', trigger: 'change' }
        ],
        'packageRequest.remarks': [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        'packageRequest.story': [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        'packageRequest.intro': [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        'packageRequest.freightTemplateId': [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        'packageRequest.firstUpSelfTime': [
          { required: true, message: '请选择', trigger: 'change' }
        ],
      },
      freightList: []
    }
  },
  created() {
    if (this.id) {
      this.getInfo()
    }
    this.getTagList()
    this.getAllTpl()
  },
  updated() {
    // console.log(this.tempGoodsCheck, 6666);
  },
  methods: {
    // tab切换
    syncSkuNumber (e) {
      if (e.name === 'log') {
        this.getLogList()
      }
    },
    // 套餐上下架记录列表
    getLogList () {
      this.request({
        url: '/bsnl-product/actionLog/page',
        method: 'post',
        data: { ...this.listQuery, typeCode: 'package', foreignKey: this.$route.query.packageId }
      }).then(({data2, totalCount}) => {
        this.goodsLogList = data2;
        this.listTotal = totalCount;
        this.listLoading = false;
      }).catch(err => {
        console.log(err);
        this.goodsLogList = [];
        this.listTotal = 0;
        this.listLoading = false;
      });
    },
    // 套餐上下架记录 分页页数
    handleSizeChange (value) {
      this.listQuery.pageSize = value;
      this.getLogList()
    },
    // 套餐上下架记录 分页页码
    handleCurrentChange(val){
      this.listQuery.pageIndex = val;
      this.getLogList();
    },
    addCommon() {
      this.commonForm()
    },
    fomatTime(e) {
      this.formData.packageRequest.firstUpSelfTime = e
    },
    // 获取模板列表
    getAllTpl() {
      getAllList()
        .then(res => {
          if (res.code == 0) {
            this.freightList = res.data
          } else {
            this.$message({
              type: 'error',
              message: res.msg,
              duration: 2000
            })
          }
        })
        .catch(err => {
          this.$message({
            type: 'error',
            message: '未知错误',
            duration: 2000
          })
        })
    },
    getInfo() {
      this.request({
        url: '/bsnl-product/package/details',
        method: 'get',
        params: {
          id: this.id,
          userId: this.$store.getters.userId
        }
      })
        .then(({ data }) => {
          if (data.packageAutoManage) {
            data.packageRequest.timeRange = [
              data.packageAutoManage.startTime,
              data.packageAutoManage.endTime
            ]
          }
          data.packageAutoManage = data.packageAutoManage
            ? data.packageAutoManage
            : {}
          data.packageGoodsList.map(item => {
            item.editSku = false
            item.goodsAttr.map(subItem => {
              subItem.skuNumber = subItem.skuNumber / (subItem.sameCount || 1)
              subItem.distributedSkuNumber = subItem.skuNumber
            })
            if (item.packageGoodsType) {
              this.tempGoodsCheck.push({
                id: item.id,
                goodsId: item.goodsId,
                name: item.goodsName
              })
            } else {
              this.tempPresentGoodsCheck.push({
                id: item.id,
                goodsId: item.goodsId,
                name: item.goodsName
              })
            }
          })
          data.packageRequest.freightTemplateId = data.packageRequest
            .freightTemplateId
            ? data.packageRequest.freightTemplateId + ''
            : ''
          this.formData = data
          this.formData.packageRequest.maximumCommission =
            this.formData.packageRequest.maximumCommission || 0

          this.tempTagCheck = data.packageTagList.map(item =>
            parseInt(item.tagId)
          )
          this.tempGoodsCheck = []
          this.tempPresentGoodsCheck = []
          this.commontGoods.push({
            value: data.packageRequest.packageId,
            label: data.packageRequest.name
          })
        })
        .catch(err => {
          console.log(err)
        })
    },
    getTagList() {
      getTagList().then(({ data }) => {
        this.tags = data ? data : []
      })
    },
    chooseGoods() {
      //let goodsCheck = type ? this.tempGoodsCheck.concat() : this.tempPresentGoodsCheck.concat();
      this.checkGoods([], -1, false, null).then(val => {
        this.goodsLoading = true
        /*let goodsList = this.formData.packageGoodsList.filter(item => item.packageGoodsType===type);
          let otherGoodsList = this.formData.packageGoodsList.filter(item => item.packageGoodsType!==type);
          let needDelGoods = differenceBy(goodsList, val, 'goodsId');
          let needAddGoods = differenceBy(val, goodsList, 'goodsId');
          this.formData.packageGoodsList = otherGoodsList.concat(differenceBy(goodsList, needDelGoods, 'goodsId'));*/
        let needAddGoods = val
        if (!needAddGoods.length) {
          this.goodsLoading = false
        }

        let p = []
        const getGoodsAttr = item =>
          new Promise((resolve, reject) => {
            this.request({
              url: '/bsnl-product/goods/details',
              method: 'get',
              params: {
                id: item.id,
                userId: this.$store.getters.userId
              }
            })
              .then(({ data }) => {
                let { goods, goodsAttr } = data
                goodsAttr.map(item => {
                  item.skuNumber = ''
                  item.soldNumber = 0
                  item.packageGoodsNumber = 1
                })
                if (!this.formData.packageRequest.cangku) {
                  this.formData.packageRequest.cangku = goods.cangku
                } else if (
                  this.formData.packageRequest.cangku !== goods.cangku
                ) {
                  this.$message({
                    type: 'error',
                    message:
                      '注意，所选新商品的仓库和已选商品不属于同一个仓库！'
                  })
                }
                this.formData.packageGoodsList.push({
                  ...item,
                  goodsType: goods.goodsType,
                  goodsName: item.name,
                  goodsAttr,
                  packageGoodsType: 1
                })
                //debugger
                // console.log(this.formData.packageGoodsList);
                resolve(data)
              })
              .catch(err => {
                reject(err)
              })
          })
        needAddGoods.map(item => {
          p.push(getGoodsAttr(item))
        })

        Promise.all(p)
          .then(resultList => {
            this.goodsLoading = false
          })
          .catch(err => {
            this.goodsLoading = false
          })

        /*needAddGoods.map((item, index) => {
              this.request({
                  url: '/bsnl-product/goods/details',
                  method: 'get',
                  params: {
                      id: item.id,
                      userId: this.$store.getters.userId
                  }
              }).then(({data}) => {
                  let {goodsAttr} = data;
                  goodsAttr.map(item=> {
                      item.skuNumber=1;
                      item.packageGoodsNumber=1;
                  });
                  this.formData.packageGoodsList.push({
                      ...item,
                      goodsName: item.name,
                      goodsAttr,
                      packageGoodsType: type
                  });

                  if(index = needAddGoods.length-1){
                      this.goodsLoading = false;
                  }
              });
          });*/
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      })
    },
    delGoods(index) {
      //console.log(goodsCheck, index, this.formData.packageGoodsList[index]);
      // goodsCheck = goodsCheck.filter(item => (item.goodsId !==this.formData.packageGoodsList[index].goodsId));
      this.formData.packageGoodsList.splice(index, 1)
      this.tempGoodsCheck = []
      this.tempPresentGoodsCheck = []
      this.formData.packageGoodsList.map(item => {
        if (item.packageGoodsType) {
          this.tempGoodsCheck.push({
            id: item.id,
            goodsId: item.goodsId,
            name: item.goodsName
          })
        } else {
          this.tempPresentGoodsCheck.push({
            id: item.id,
            goodsId: item.goodsId,
            name: item.goodsName
          })
        }
      })
      if (this.formData.packageGoodsList.length <= 0) {
        this.formData.packageRequest.cangku = ''
      }
      /*this.formData.packageGoodsList.splice(index, 1);
        this.tempGoodsCheck.splice(index, 1);
        this.reValidate();*/
    },
    delAttrVal(goodsAttr, index) {
      this.$confirm(`确定要删除吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // goodsAttr.splice(index, 1);
          goodsAttr.filter(item => item.deleteFlag !== 0)[index].deleteFlag = 0
          this.$message.success('删除成功')
        })
        .catch(err => {
          console.log(err)
        })
    },
    reValidate() {
      this.$refs.form.validateField('packageGoodsList')
      if (this.formData.packageRequest.type === 2) {
        this.$refs.form.validateField('packageRequest.num')
      }
      this.$nextTick(function() {
        if (
          this.formData.packageGoodsList.some(
            item => item.packageGoodsType === 0
          )
        ) {
          this.$refs.form.validateField('packageRequest.presentSelectedNum')
        }
      })
    },
    // 主图上传成功
    uploadSuccess(res, file) {
      this.formData.packageRequest.image = this.replaceImgUrl(res.filePath)
      this.$refs.form.validateField('packageRequest.image')
    },
    uploadImg(event) {
      const file = event.target.files[0]
      this.picFileUpload(file, res => {
        this.formData.packageGalleryList.push({
          url: this.replaceImgUrl(res.filePath),
          type: 1
        })
        this.$refs.form.validateField('packageGalleryList')
        // this.form.packageRequest.packageGalleryList = this.form.packageGalleryList;
      })
    },
    delImg(index) {
      this.formData.packageGalleryList.splice(index, 1)
    },
    // 根据兰蜜价和最高佣金计算大区价和董事价
    calcPrice() {
      let query = {
        lmPrice: this.formData.packageRequest.price,
        highestCommission: this.formData.packageRequest.maximumCommission
      }
      this.calcRDPrice(query, data => {
        this.formData.packageRequest.regionPrice = data.regionPrice
        this.formData.packageRequest.directorPrice = data.directorPrice
        this.formData.packageRequest.diamondPrice = data.diamondPrice
      })
    },
    // 根据兰蜜价和最高佣金计算大区价和董事价
    calcOtherPrice(index, subIndex) {
      let query = {
        lmPrice: this.formData.packageGoodsList[index].goodsAttr[subIndex]
          .price,
        highestCommission: this.formData.packageGoodsList[index].goodsAttr[
          subIndex
        ].maximumCommission
      }
      this.calcRDPrice(query, data => {
        this.formData.packageGoodsList[index].goodsAttr[subIndex].regionPrice =
          data.regionPrice
        this.formData.packageGoodsList[index].goodsAttr[
          subIndex
        ].directorPrice = data.directorPrice
        this.formData.packageGoodsList[index].goodsAttr[
          subIndex
        ].diamondPrice = data.diamondPrice
      })
    },
    // 上下架改变是否售卖的状态
    changeIsSell() {
      if (
        !(
          this.formData.packageRequest.upshelf ||
          this.formData.packageRequest.autoUpShelfFlag
        )
      ) {
        this.formData.packageRequest.isSell = 0
        this.formData.packageRequest.isSearched = 0
      }
      // this.calcSku();
    },
    //自动分配库存
    /*calcSku(){
        if(this.formData.packageRequest.type === 1){
          if(this.formData.packageRequest.upshelf || this.formData.packageRequest.autoUpShelfFlag){
            let goodsSkuArray = this.getTempGoodsArray();
            this.formData.packageGoodsList.map((item, index) => {
              let total = this.formData.packageRequest.packageNumber;
              item.goodsAttr.map(subItem => {
                let i = goodsSkuArray.findIndex(skuItem=>skuItem.skuCode === subItem.skuCode);
                if(goodsSkuArray[i].totalSkuNumber>=total){
                  subItem.skuNumber = total;
                  goodsSkuArray[i].totalSkuNumber -= total;
                  total = 0
                } else if(goodsSkuArray[i].totalSkuNumber>0) {
                  subItem.skuNumber = goodsSkuArray[i].totalSkuNumber;
                  total-=goodsSkuArray[i].totalSkuNumber;
                  goodsSkuArray[i].totalSkuNumber = 0;
                } else {
                  subItem.skuNumber = 0;
                }
                if(total===0){
                  return;
                }
              })
            });
          }
          else{
            this.formData.packageGoodsList.map(item => {
              item.goodsAttr.map(subItem => subItem.skuNumber = 0)
            });
          }
        }
      },*/

    //修改保存库存
    modifySku(goodsIndex) {
      let totalSku = 0
      let currentGoods = this.formData.packageGoodsList[goodsIndex]
      if (this.formData.packageRequest.type !== 1) {
        currentGoods.editSku = false
        return
      }

      currentGoods.goodsAttr.map(item => {
        totalSku += item.skuNumber
      })
      if (totalSku < this.formData.packageRequest.packageNumber) {
        this.$alert(
          `该商品须分配总库存：${this.formData.packageRequest.packageNumber}，\n已分配总库存：${totalSku},`,
          '库存分配不足',
          {
            confirmButtonText: '确定'
          }
        )
      } else {
        // let sameGoods = this.formData.packageGoodsList.filter(item => item.goodsId === currentGoods.goodsId);
        currentGoods.editSku = false
      }
    },

    getTempGoodsArray() {
      let goodsSkuArray = []
      this.formData.packageGoodsList.map(item => {
        if (item.goodsType === 1 && item.goodsAttr.length) {
          item.goodsAttr.map(subItem => {
            if (subItem.deleteFlag) {
              goodsSkuArray.push({
                skuCode: subItem.skuCode,
                totalSkuNumber: Math.floor(
                  ((subItem.distributedSkuNumber || 0) +
                    subItem.totalSkuNumber) /
                    subItem.packageGoodsNumber
                )
              })
            }
          })
        }
      })

      return goodsSkuArray
    },
    // 下架
    offShelves() {
      this.$confirm('确定下架该套餐?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.request({
            url: '/bsnl-product/package/updateUpshelfStatus',
            method: 'post',
            data: {
              id: this.id,
              upshelf: 0,
              isSearched: 0
            }
          })
            .then(() => {
              this.$message.success('下架成功')
              this.$router.replace({
                name: 'activityPackageEdit',
                params: { id: this.id },
                query: { pageType: 'edit', packageId: this.$route.query.packageId }
              })
              this.reload()
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },

    save() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return false
        }
        let timeRange = this.formData.packageRequest.timeRange
        if (timeRange && timeRange.length > 0) {
          this.formData.packageAutoManage.startTime = this.formatDate(
            timeRange[0],
            'YYYY-MM-DD HH:mm:ss'
          )
          this.formData.packageAutoManage.endTime = this.formatDate(
            timeRange[1],
            'YYYY-MM-DD HH:mm:ss'
          )
        }

        this.formData.packageTagList = this.tempTagCheck.map(item => ({
          tagId: item
        }))

        this.formData.goodsAttr = []
        let noSkuGoods = []
        let saveSkuFlag = false
        this.formData.packageGoodsList.map(item => {
          if (item.editSku) {
            saveSkuFlag = true
          }
          if (item.goodsAttr.length) {
            this.formData.goodsAttr = this.formData.goodsAttr.concat(
              item.goodsAttr
            )
          } else {
            noSkuGoods.push(item)
          }
        })

        if (saveSkuFlag) {
          this.$message.warning('存在未保存的库存分配，请先保存')
        } else if (!noSkuGoods.length) {
          /*if(this.formData.goodsAttr.some(item => !(item.totalSkuNumber+(item.distributedSkuNumber||0))&&item.deleteFlag)){
              this.$message.warning('存在0库存的规格商品，请先移除再保存');
          } else */
          // console.log('goodsAttr: \n', JSON.stringify(this.formData.goodsAttr));
          this.btnLoading = true
          let url = '/bsnl-product/package/create'
          if (this.isEdit) {
            url = '/bsnl-product/package/update'
          }
          this.formData.packageRequest.freightTemplateId = Number(
            this.formData.packageRequest.freightTemplateId
          )
          if (this.formData.packageRequest.maximumCommission == 0) {
            this.formData.packageRequest.regionPrice = this.formData.packageRequest.price
            this.formData.packageRequest.diamondPrice = this.formData.packageRequest.price
            this.formData.packageRequest.directorPrice = this.formData.packageRequest.price
          }
          this.formData.goodsAttr.forEach((item, index) =>{
            if (item.maximumCommission == 0) {
              item.regionPrice = item.price
              item.diamondPrice = item.price
              item.directorPrice = item.price
            }
          })
          if (!this.formData.packageGoodsList.some(item=>item.packageGoodsType===0)) {
            delete this.formData.packageRequest.presentSelectedNum
          }
          this.request({
            url,
            method: 'post',
            data: this.formData
          })
            .then(() => {
              if (this.isEdit) {
                this.$message.success('编辑套餐成功')
              } else {
                this.$message.success('新建套餐成功')
              }
              this.$router.push({ name: 'activityPackage' })
            })
            .catch(err => {
              console.error(err)
              this.btnLoading = false
            })
        } else {
          let msg = '商品【'
          noSkuGoods.map((item, index) => {
            msg += item.name
            msg +=
              index === noSkuGoods.length - 1
                ? '】没有SKU信息，请先移除对应的商品'
                : '、'
          })
          this.$message({
            message: msg,
            type: 'warning'
          })
        }
      })
    }
  }
}
</script>
<style lang="scss">
.package-container > section {
  padding: 24px;
  background: #fff;
  .section-header {
    margin-bottom: 32px;
    padding: 12px;
    background: #f8f8f8;
    box-sizing: border-box;
    span {
      color: #333;
      font-size: 14px;
      line-height: 12px;
      padding: 0 12px;
      border-left: 1px solid #409eff;
    }
  }

  .el-input.el-input--medium.el-input--suffix {
    width: 100% !important;
  }
  .el-table__body .el-select,
  .el-table__body .el-input {
    width: 100% !important;
  }
  .hide-close {
    .el-icon-circle-close {
      display: none;
    }
  }
}
</style>
